package com.budwk.app.sqfw.services.customservice;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.budwk.app.common.config.AppException;
import com.budwk.app.exception.ServiceException;
import com.budwk.app.sqfw.bo.RoomSafetyBo;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.vo.SqfwCustomForAdminCommonVO;
import com.budwk.app.sqfwV2.dto.RoomSafetyAssistantDTO;
import com.budwk.app.sqfwV2.service.roomSafety.ThirdPartyService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.util.ClassUtil;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.app.util.poiUtils.PictureUtils;
import com.budwk.app.util.poiUtils.excelPictureConfigBO.ExcelFileCreateParamBO;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 房安助手
 * @BelongsProject: dfxy-shequ
 * @Author: yangweimin
 * @CreateTime: 2024-06-27  16:13
 * @Description: TODO
 */
@IocBean
@Slf4j
public class RoomSafetyService {
    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    /**
     * 获取数据
     * @param bean
     * @return
     */
    public Pagination list(SqfwCustomForAdminCommonVO bean) {
        // 构造查询条件
        Criteria criteria = buildQueryCond(bean);
        log.info("DoorThreeCareForAdminServiceImpl-list-SQL: {}", criteria.toString());
        Pagination pagination = sqfwFormsummaryNewService.listPage(bean.getPageNo(), bean.getPageSize(), criteria);

        return pagination;
    }

    /**
     * 下载表格
     * @param bean
     * @return
     */
    public String downExcelByQuery(SqfwCustomForAdminCommonVO bean) {
        Criteria criteria = buildQueryCond(bean);
        List<Sqfw_formSummary_new> formSummaryNewList = sqfwFormsummaryNewService.query(criteria);

        return downExcel(formSummaryNewList);
    }

    /**
     * 下载表格
     * @param idList
     * @return
     */
    public String downExcelByIds(List<String> idList) {
        if (idList.size() == 0) throw new ServiceException("请选择要导出的数据");
        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary_new::getId, "in", idList);
        List<Sqfw_formSummary_new> formSummaryNewList = sqfwFormsummaryNewService.query(cnd);

        return downExcel(formSummaryNewList);
    }

    private String downExcel(List<Sqfw_formSummary_new> formSummaryNewList) {
        if (formSummaryNewList.size() == 0) throw new ServiceException("暂无数据");
        List<Map<String, Object>> mapList = new ArrayList<>();
        int i = 0;
        for (Sqfw_formSummary_new formSummaryNew : formSummaryNewList) {
            Map<String, Object> map = new HashMap<>();
            i ++;
            RoomSafetyAssistantDTO dto = JSON.parseObject(formSummaryNew.getParamData(), RoomSafetyAssistantDTO.class);
            map.put("num", i);
            map.put(ClassUtil.getField(RoomSafetyAssistantDTO::getHouseGrade), dto.getHouseGrade());
            map.put(ClassUtil.getField(RoomSafetyAssistantDTO::getHouseName), dto.getHouseName());
            map.put(ClassUtil.getField(RoomSafetyAssistantDTO::getAddress), dto.getAddress());
            map.put(ClassUtil.getField(RoomSafetyAssistantDTO::getCreateDate), dto.getCreateDate());
            map.put(ClassUtil.getField(RoomSafetyAssistantDTO::getWhetherThereIsAnyHiddenDanger), "0".equals(dto.getWhetherThereIsAnyHiddenDanger())?"是":"否");
            map.put(ClassUtil.getField(RoomSafetyAssistantDTO::getHouseConditionDescription), dto.getHouseConditionDescription());
            map.put(ClassUtil.getField(RoomSafetyAssistantDTO::getReportName), dto.getReportName());
            map.put(ClassUtil.getField(RoomSafetyAssistantDTO::getReportTel), dto.getReportTel());
            //图片处理
            List<byte[]> imgBytes1 = getByte(dto.getVisitPictures(), 1);
            map.put(ClassUtil.getField(RoomSafetyAssistantDTO::getVisitPictures), imgBytes1);
            List<byte[]> imgBytes2 = getByte(dto.getConstructionPermit(), 1);
            map.put(ClassUtil.getField(RoomSafetyAssistantDTO::getConstructionPermit), imgBytes2);

            map.put(ClassUtil.getField(Sqfw_formSummary_new::getDistrict), formSummaryNew.getDistrict());
            map.put(ClassUtil.getField(Sqfw_formSummary_new::getCommunity), formSummaryNew.getCommunity());
            map.put(ClassUtil.getField(Sqfw_formSummary_new::getCounty), formSummaryNew.getCounty());
            map.put(ClassUtil.getField(Sqfw_formSummary_new::getFillDate), DateUtil.format(formSummaryNew.getFillDate(), "yyyy-MM-dd hh:mm:ss"));

            mapList.add(map);
        }

        String templatePath = CommonFormOfficeUtils.getTemplatePathByOS("helper/roomSafety.xlsx");

        String fileName = "房安助手";

        ExcelFileCreateParamBO excelFileCreateParam = new ExcelFileCreateParamBO();
        excelFileCreateParam.setTemplatePath(templatePath);
        excelFileCreateParam.setSheetParam(new HashMap<>());
        excelFileCreateParam.setDataList(mapList);
        excelFileCreateParam.setClazz(RoomSafetyBo.class);
        excelFileCreateParam.setFileName(fileName);
        excelFileCreateParam.setReturnWebUrlFlag(true);

        return CommonFormOfficeUtils.createExcelAndUpload(excelFileCreateParam);
    }

    private List<byte[]> getByte(String url, int size) {
        if (StringUtils.isBlank(url)) return new ArrayList<>();
        String urls[] = url.split(",");
        List<byte[]> bytes = new ArrayList<>();
        for (int i = 0; i < (size > urls.length ? urls.length : size); i ++) {
            byte[] b = ThirdPartyService.v_image(urls[i], "0");
            if (b.length != 0) {
                bytes.add(b);
            }
        }
        return bytes;
    }

    public Criteria buildQueryCond(SqfwCustomForAdminCommonVO bean) {
        Criteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        // 组装查询条件
        if (StringUtils.isNotBlank(bean.getPageOrderName()) && Strings.isNotBlank(bean.getPageOrderBy())) {
            if (bean.getPageOrderBy().equals(CommonConstants.ASC)) {
                cri.getOrderBy().asc(bean.getPageOrderName());
            }
            if (bean.getPageOrderBy().equals(CommonConstants.DESC)) {
                cri.getOrderBy().desc(bean.getPageOrderName());
            }
        } else {
            cri.getOrderBy().desc(Sqfw_formSummary_new::getFillDate);
        }
        if (StringUtils.isNotBlank(bean.getName())) {
            criSql.and("param_data->>'houseName'", "like", bean.getName());
        }
        if (StringUtils.isNotBlank(bean.getWhetherThereIsAnyHiddenDanger())) {
            criSql.and("param_data->>'whetherThereIsAnyHiddenDanger'", "=", bean.getWhetherThereIsAnyHiddenDanger());
        }
        if (bean.getFillStartDate() != null) {
            criSql.and(Sqfw_formSummary_new::getFillDate, ">=", bean.getFillStartDate());
        }
        if (bean.getFillEndDate() != null) {
            criSql.and(Sqfw_formSummary_new::getFillDate, "<=", bean.getFillEndDate());
        }
        // 类型
        criSql.andEquals(Sqfw_formSummary_new::getType, bean.getType());

        // 区域5级检查
        // 省
        if (StringUtils.isNotBlank(bean.getProvince())) {
            criSql.andEquals(Sys_user::getProvince, bean.getProvince());
        }
        // 市
        if (StringUtils.isNotBlank(bean.getCity())) {
            criSql.andEquals(Sys_user::getCity, bean.getCity());
        }
        // 区
        if (StringUtils.isNotBlank(bean.getDistrict())) {
            criSql.andEquals(Sys_user::getDistrict, bean.getDistrict());
        }
        // 街道
        if (StringUtils.isNotBlank(bean.getCounty())) {
            criSql.andEquals(Sys_user::getCounty, bean.getCounty());
        }
        // 辖区
        if (StringUtils.isNotBlank(bean.getCommunity())) {
            criSql.andEquals(Sys_user::getCommunity, bean.getCommunity());
        }
        return cri;
    }
}
